import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:get/get.dart';
import 'package:xiaomishop/app/service/MyScreenExtention.dart';

import '../../../routes/app_pages.dart';
import '../../../service/iconAdapter.dart';
import '../../../service/keep_alive_wrapper.dart';
import '../controllers/main_controller.dart';

class MainView extends GetView<MainController> {
  const MainView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return KeepAliveWrapper(
        child: Scaffold(
      //使用相对布局，使得appbar覆盖在上面
      body: Stack(children: [
        Positioned(
            top: -40,
            left: 0,
            right: 0,
            bottom: 0,
            child: NestedScrollView(
              body: _mainListView(controller),
              headerSliverBuilder:
                  (BuildContext context, bool innerBoxIsScrolled) {
                return <Widget>[
                  SliverList(delegate: SliverChildListDelegate([]))
                ];
              },
            )),
        Positioned(
          top: 0,
          left: 0,
          right: 0,
          //Opacity可以改变透明度
          child: _appBar(controller),
        )
      ]),
    ));
  }

  /**
   * app首页列表部分
   */
  _mainListView(MainController controller) {
    return ListView(controller: controller.scrollController, children: [
      _bannerTopView(),
      _bannerLogoView(),
      _catergoryView(),
      _bannerCenterView(),
      _textCenterView(),
      _hotGoodsView(),
      _textBottomView(),
      _bottomGoodsView(),
      _errorView(),
    ]);
  }

  /**
   * app首页顶部部分
   */
  _appBar(MainController controller) {
    return InkWell(
        child: Container(
            margin: EdgeInsets.fromLTRB(0, 70.hh, 0, 0),
            height: 100.hh,
            child: Stack(children: [
              Obx(() => Positioned(
                  child: Opacity(
                      opacity: controller.actionBarApla.value,
                      child: Container(
                          decoration:
                              const BoxDecoration(color: Colors.white70))))),
              Obx(() => Positioned(
                  left: controller.actionMargin.value,
                  right: 220.ww,
                  top: 0,
                  bottom: 0,
                  child: Align(
                    //搜索输入框
                    child: _searchView(controller),
                  ))),
              Obx(() => Positioned(
                  left: 40.ww,
                  bottom: 0,
                  top: 0,
                  child: Opacity(
                      opacity: controller.miIconApla.value,
                      child: Icon(IconAdapter.xiaomi)))),
              Positioned(
                  right: 40.ww,
                  bottom: 0,
                  top: 0,
                  child: Image.asset('assets/images/image_msg.png',
                      width: 60.ww, height: 60.hh)),
              Positioned(
                  right: 120.ww,
                  bottom: 0,
                  top: 0,
                  child: Image.asset('assets/images/image_type.png',
                      width: 60.ww, height: 60.hh))
            ])),
        onTap: () {
          Get.toNamed(Routes.GOOD_SEARCH);
        });
  }

  _searchView(MainController controller) {
    return Container(
      height: 80.hh,
      decoration: BoxDecoration(
          color: const Color(0xFFC1C1C3),
          borderRadius: BorderRadius.circular(26)),
      child: Stack(
        children: [
          Positioned(
            left: 100.ww,
            top: 0,
            bottom: 0,
            child: Align(
              alignment: Alignment.center,
              child: Text(
                "空调",
                textAlign: TextAlign.center,
                style:
                    TextStyle(fontSize: 40.ss, color: const Color(0xFF8A8A8A)),
              ),
            ),
          ),
          Positioned(
              bottom: 0,
              top: 0,
              left: 30.ww,
              child: Align(
                  alignment: Alignment.centerLeft,
                  child: Image.asset('assets/images/image_search.png',
                      width: 55.ww, height: 55.hh))),
          Positioned(
              bottom: 0,
              top: 0,
              right: 30.ww,
              child: Align(
                  alignment: Alignment.centerRight,
                  child: Image.asset('assets/images/image_q_scan.png',
                      width: 55.ww, height: 55.hh)))
        ],
      ),
    );
  }

  _catergoryView() {
    return Container(
        decoration: const BoxDecoration(color: Colors.white70),
        width: 700.ww,
        height: 370.hh,
        child: Obx(() => Swiper(
            pagination: const SwiperPagination(builder: SwiperPagination.rect),
            loop: false,
            itemCount: controller.mCategoryItems.value.length ~/ 10,
            //整出
            itemBuilder: (context, index) {
              return GridView.builder(
                itemCount: 10,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    mainAxisExtent: 160.hh,
                    //item纵间距
                    // childAspectRatio: 1, // 宽高比为 1,高度使用了具体的高度，就不需要设置宽高比
                    crossAxisCount: 5),
                itemBuilder: (context, i) {
                  var url = controller.mCategoryItems[index * 10 + i].pic;
                  var title = controller.mCategoryItems[index * 10 + i].title;
                  url.replaceAll("\\", "/");
                  return InkWell(
                      onTap: () {
                        Get.toNamed(Routes.GOODLIST, arguments: {
                          "id": controller.mCategoryItems[index].sid
                        });
                      },
                      child: Column(children: [
                        SizedBox(
                            // decoration:
                            //     const BoxDecoration(color: Colors.green),
                            width: 100.ww,
                            height: 100.hh,
                            child: Image.network(
                                "https://xiaomi.itying.com/$url",
                                fit: BoxFit.fitHeight)),
                        Text(
                          title,
                          style: TextStyle(fontSize: 30.ss),
                        )
                      ]));
                },
              );
            })));
  }

  _bannerTopView() {
    return SizedBox(
        width: 1080.ww,
        height: 600.hh,
        child: Obx(() => Swiper(
              itemBuilder: (context, index) {
                var picUrl =
                    "https://xiaomi.itying.com/${controller.mBannerItems[index].pic}";
                //对//符号进行处理
                picUrl.replaceAll("\\", "/");
                return Image.network(
                  picUrl,
                  fit: BoxFit.fill,
                );
              },
              loop: true,
              duration: 300,
              autoplay: true,
              itemCount: controller.mBannerItems.length,
              pagination:
                  const SwiperPagination(builder: SwiperPagination.rect),
            )));
  }

  _bannerCenterView() {
    return Container(
      margin: EdgeInsets.fromLTRB(20.ww, 0, 20.ww, 0),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20.ww),
          image: DecorationImage(
              fit: BoxFit.cover,
              image: AssetImage("assets/images/xiaomiBanner2.png"))),
      height: 320.hh,
    );
  }

  _textCenterView() {
    return Padding(
        padding: EdgeInsets.fromLTRB(20.ww, 20.hh, 20.ww, 20.hh),
        child:
            Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          Text("热销甄选",
              style: TextStyle(
                  fontSize: 52.ss,
                  color: Colors.black87,
                  fontWeight: FontWeight.bold)),
          Text("更多推荐>",
              style: TextStyle(fontSize: 46.ss, color: Colors.black87))
        ]));
  }

  //热销商品布局
  _hotGoodsView() {
    return Row(children: [
      SizedBox(width: 20.ww),
      Expanded(
          flex: 1,
          child: Container(
              height: 650.hh,
              // decoration: BoxDecoration(color: Colors.red),
              child: Obx(() => Swiper(
                    itemBuilder: (context, index) {
                      String picUrl = controller.mHotGoogBannerItems[index].pic;
                      //对//符号进行处理
                      picUrl.replaceAll("\\", "/");
                      return Container(
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(20.ww),
                            image: DecorationImage(
                                fit: BoxFit.cover,
                                image: NetworkImage(
                                    "https://xiaomi.itying.com/$picUrl"))),
                      );
                    },
                    loop: false,
                    duration: 300,
                    autoplay: true,
                    itemCount: controller.mHotGoogBannerItems.length,
                    pagination:
                        const SwiperPagination(builder: SwiperPagination.rect),
                  )))),
      SizedBox(width: 30.ww),
      Expanded(
          flex: 1,
          child: Container(
              height: 650.hh,
              child: Obx(() => Column(
                      children: controller.mHotGoodModelItems
                          .asMap()
                          .entries
                          .map((good) {
                    //使用循环便利的方式
                    var pic = "https://xiaomi.itying.com/${good.value.pic}";
                    pic.replaceAll("\\", "/");
                    return Expanded(
                        flex: 1,
                        child: Container(
                            margin: EdgeInsets.fromLTRB(
                                0, 0, 0, good.key == 2 ? 0 : 10.hh),
                            padding: EdgeInsets.fromLTRB(10.ww, 0, 0, 0),
                            decoration: BoxDecoration(
                                color: Colors.blue.shade50,
                                borderRadius: BorderRadius.circular(20.ww)),
                            child: Row(children: [
                              Expanded(
                                  flex: 6,
                                  child: Container(
                                      margin:
                                          EdgeInsets.fromLTRB(10.ww, 0, 0, 0),
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Text("${good.value.title}",
                                              style: TextStyle(
                                                fontSize: 26.ss,
                                              )),
                                          Text("${good.value.subTitle}",
                                              style:
                                                  TextStyle(fontSize: 22.ss)),
                                          Text("众筹价￥${good.value.price}元",
                                              style:
                                                  TextStyle(fontSize: 22.ss)),
                                        ],
                                      ))),
                              Expanded(
                                  flex: 3,
                                  child: Container(
                                      alignment: Alignment.center,
                                      width: 140.ww,
                                      height: 140.hh,
                                      child: Image.network(pic,
                                          fit: BoxFit.cover))),
                            ])));
                  }).toList())))),
      SizedBox(width: 20.ww)
    ]);
  }

  _bannerLogoView() {
    return Container(
        decoration: BoxDecoration(color: Colors.white),
        width: 1080.ww,
        height: 100.hh,
        child: Image.asset("assets/images/xiaomiBanner.png"));
  }

  _bottomGoodsView() {
    return Obx(() => Container(
        margin: EdgeInsets.fromLTRB(20.ww, 0, 20.ww, 0),
        child: MasonryGridView.count(
          crossAxisCount: 2,
          ////本身不滚动，让外面的 listview 来滚动
          physics: NeverScrollableScrollPhysics(),
          ////收缩，让元素高度自适应
          shrinkWrap: true,

          mainAxisSpacing: 20.ww,
          crossAxisSpacing: 20.ww,
          itemCount: controller.mBottomGoodModelItems.length,
          itemBuilder: (context, index) {
            var good = controller.mBottomGoodModelItems[index];
            var pic = "https://xiaomi.itying.com/${good.pic}";
            pic.replaceAll("\\", "/");
            return Container(
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20.ww)),
              child: Column(
                children: [
                  Image.network(pic),
                  Container(
                      alignment: Alignment.centerLeft,
                      padding: EdgeInsets.fromLTRB(10.ww, 5.hh, 10.ww, 5.hh),
                      child: Text("${good.title}",
                          style: TextStyle(fontSize: 40.ss))),
                  Container(
                      alignment: Alignment.centerLeft,
                      padding: EdgeInsets.fromLTRB(10.ww, 0, 5.hh.ww, 5.hh),
                      child: Text("${good.subTitle}",
                          style: TextStyle(fontSize: 30.ss))),
                  Container(
                      alignment: Alignment.centerLeft,
                      padding: EdgeInsets.fromLTRB(10.ww, 5.hh, 10.ww, 5.hh),
                      child: Text("￥ ${good.price}",
                          style:
                              TextStyle(fontSize: 35.ss, color: Colors.red))),
                ],
              ),
            );
          },
        )));
  }

  _errorView() {
    return Container(child: Obx(() => Text("${controller.errorInfo.value}")));
  }
}

_textBottomView() {
  return Padding(
      padding: EdgeInsets.fromLTRB(20.ww, 20.hh, 20.ww, 20.hh),
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        Text("人气上新",
            style: TextStyle(
                fontSize: 52.ss,
                color: Colors.black87,
                fontWeight: FontWeight.bold)),
        Text("最新上架>", style: TextStyle(fontSize: 46.ss, color: Colors.black87))
      ]));
}
// Column(
// children: [Text("空气炸锅"), Text("空气炸锅"), Text("空气炸锅")]),
// Container(
// height: 280.hh,
// child: Image.network(
// "https://www.itying.com/images/kaoxiang.png"))
